package com.blackhorse.service.impl;

import com.alibaba.fastjson.JSON;
import com.blackhorse.dao.OrderDao;
import com.blackhorse.domain.Order;
import com.blackhorse.domain.Product;
import com.blackhorse.service.OrderService;
import com.blackhorse.service.ProductService;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 测试seata分布式事务的订单业务层
 */
@Slf4j
@Service
public class OrderServiceImpl5 {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductService productService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //seata全局事务控制
//    @GlobalTransactional
    public Order createOrder(Integer pid) {
        log.info("订单微服务-下单-开始 pid:{}", pid);

        Product product = productService.findByPid(pid);
        log.info("订单微服务-下单-查询到商品信息 pid:{} product:{}", pid, JSON.toJSONString(product));

        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }

        //判断是否走容错逻辑，测试时直接停掉商品微服务即可模拟
        if (product.getPid() == -100) {
            Order order = new Order();
            order.setOid(-100);
            order.setPname("下单失败");
            return order;
        }

        //下单操作
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderDao.save(order);

        //扣减商品库存
        productService.reduceInventory(pid, order.getNumber());


        //生产下单成功MQ，参数1为topic，参数2为消息体
//        rocketMQTemplate.convertAndSend("order-topic", order);
        log.info("订单微服务-下单-创建订单成功 order:{}", JSON.toJSONString(order));
        return order;
    }
}
